const url = require("url");

let invokeMethod = this;
this._get = {};
this._post = {};

let app = function (req, res) {
    changeRes(res);
    let pathName = url.parse(req.url).pathname;
    if (pathName === "/favicon.ico") {
        return;
    }
    try {
        let method = req.method.toLocaleLowerCase();
        let postStr = "";
        if (method === "post") {
            req.on("data", function (data) {
                postStr += data;
            });
            req.on("end", function () {
                req.queryParams = decodeURI(postStr);
                invokeMethod["_" + method][pathName](req, res);
            });
        } else {
            invokeMethod["_" + method][pathName](req, res);
        }
    } catch (e) {
        console.log(e);
        res.end("404 no router!");
    }
}

function changeRes(res) {
    res.send = function (data) {
        res.writeHead(200, {"Content-Type": "text/html;charset=utf-8"});
        res.end(data);
    }
}

app._get = function (pathName, callback) {
    invokeMethod["_get"][pathName] = callback;
    /*这是在注册方法，实际效果如下：
    invokeMethod["login"] = function (req, res) {
        console.log("this is app.get()");
    }*/
}

app._post = function (pathName, callback) {
    invokeMethod["_post"][pathName] = callback;
}

module.exports = app;